package com.xdjk.networkdemo.net;

import android.os.Handler;
import android.os.Looper;

import com.orhanobut.logger.Logger;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.BufferedSink;

/**
 * 文件上传进度RequestBody
 * Created by zhanghs on 2017/8/17.
 */

public class ProgressRequestBody extends RequestBody {
    private final UploadOCallBack mListener;
    private File mFile;
    private String mPath;
    private static final int DEFAULT_BUFFER_SIZE = 4096;
    private MediaType mMediaType;

    public ProgressRequestBody(final File file,MediaType mediaType, final UploadOCallBack listener) {
        mFile = file;
        mListener = listener;
        mMediaType = mediaType;
    }

    @Override
    public MediaType contentType() {
        return mMediaType;
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        long fileLength = mFile.length();
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        FileInputStream in = new FileInputStream(mFile);
        long uploaded = 0;

        try {
            int read = 0;
            Handler handler = new Handler(Looper.getMainLooper());
            while ((read = in.read(buffer)) != -1) {

                uploaded += read;
                sink.write(buffer, 0, read);
                handler.post(new ProgressUpdater(uploaded, fileLength));
            }
            // update progress on UI thread
//            handler.post(new ProgressUpdater(uploaded, fileLength));
        } finally {
            in.close();
        }
    }
    private class ProgressUpdater implements Runnable {
        private long mUploaded;
        private long mTotal;
        public ProgressUpdater(long uploaded, long total) {
            mUploaded = uploaded;
            mTotal = total;
        }

        @Override
        public void run() {
            Logger.d("mUploaded="+mUploaded+" mTotal="+mTotal);
            mListener.onProgressChange(mUploaded, mTotal);
        }
    }
}
